﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Threading.Tasks;
using WebApi.Helpers;
using WebApi.Model;

namespace WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductListController : BaseController
    {
        public ProductListController(ILogger<ProductListController> logger) : base(logger)
        {
        }

        [HttpPost("Add")]
        public async Task<ReturnModel> Add(ProductList model)
        {
            return await Save(model, true);
        }

        [HttpPost("Update")]
        public async Task<ReturnModel> Update(ProductList model)
        {
            return await Save(model, false);
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="model"></param>
        /// <param name="isInsert"></param>
        /// <returns></returns>
        private async Task<ReturnModel> Save(ProductList model, bool isInsert)
        {
            try
            {
                logger.LogDebug($"isInsert={isInsert};" + JsonConvert.SerializeObject(model));
                if (DbHelper.ProductList.IsAny(c => c.product == model.product && c.id != model.id))
                    return logger.Code_202("货物名称已存在");
                else if (isInsert)
                    await DbHelper.ProductList.InsertAsync(model);
                else
                    await DbHelper.GetDbConn().Updateable(model).ExecuteCommandAsync();
                LogToDB("ProductList", isInsert ? "新增" : "更新", $"参数：{JsonConvert.SerializeObject(model)}", "成功");
                return new ReturnModel { Count = 1 };
            }
            catch (Exception ex)
            {
                LogToDB("ProductList", isInsert ? "新增" : "更新", $"参数：{JsonConvert.SerializeObject(model)}", "异常", $"{nameof(Save)}-{ex.Message}");
                return logger.ErrorModel(nameof(ProductListController) + "-" + nameof(Save), ex);
            }
        }

        /// <summary>
        /// 获取货物名称下拉框数据
        /// </summary>
        /// <returns></returns>
        [HttpPost("SelectList")]
        public async Task<ReturnModel> SelectList()
        {
            try
            {
                var list = await DbHelper.ProductList.AsQueryable().Select(it => it.product).ToListAsync();
                return new ReturnModel { Count = list.Count, Data = list };
            }
            catch (Exception ex)
            {
                return logger.ErrorModel($"{nameof(ProductListController)}/{nameof(SelectList)}", ex);
            }
        }
    }
}